package application.mvc.sys.config.camera;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

import com.jfinal.kit.StrKit;

import application.common.model.Camera;
import application.common.render.CameraProperty;
import application.common.ui.ProgressStage;
import application.common.util.LayerUtil;
import application.common.util.RouteUtil;
import application.common.util.ShiroUtil;
import application.common.util.UuidUtil;
import javafx.animation.Animation;
import javafx.animation.Interpolator;
import javafx.animation.KeyFrame;
import javafx.animation.RotateTransition;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.util.Duration;

public class CameraController implements Initializable{

	@FXML
	private Label headerLabel;
	
	@FXML
	private Label copyrightLabel;
	
	@FXML
	private Label usernameLabel;
	
	@FXML
	private Label roleNameLabel;
	
	@FXML
	private ImageView portraitImageView;

	@FXML
	private TableView< CameraProperty> cameraTableView;
	
	@FXML
	private Pane timerOutLinePane;

	@FXML
	private Pane timerInLinePane;

	@FXML
	private Label timerLabel;
	private Timeline animation;
	private RotateTransition rotateTransitionOut;
	private RotateTransition rotateTransitionIn;

	private final ObservableList<CameraProperty> data = FXCollections.observableArrayList();
	private boolean isDestroy=false;
	@SuppressWarnings("unchecked")
	public void initialize(URL location, ResourceBundle resources) {
		
		headerLabel.setText(ShiroUtil.getSoftName());
		copyrightLabel.setText(ShiroUtil.getCopyright());
		
		if(ShiroUtil.getUser()!=null) {
			portraitImageView.setImage(ShiroUtil.getUser().getPortrait());
			usernameLabel.setText(ShiroUtil.getUser().getName());
			roleNameLabel.setText(ShiroUtil.getUser().getRoleName());
		}
		cameraTableView.setEditable(true);

		TableColumn<CameraProperty, String> boardIdColumn = new TableColumn<CameraProperty, String>("标识");
		boardIdColumn.setMinWidth(150);
		boardIdColumn.setCellValueFactory(new PropertyValueFactory<CameraProperty, String>("id"));
		boardIdColumn.setVisible(false);

		TableColumn<CameraProperty, String> nameColumn = new TableColumn<CameraProperty, String>("名称");
		nameColumn.setMinWidth(150);
		nameColumn.setCellValueFactory(new PropertyValueFactory<CameraProperty, String>("name"));
		nameColumn.setCellFactory(TextFieldTableCell.<CameraProperty>forTableColumn());
		nameColumn.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<CameraProperty, String>>() {
			public void handle(CellEditEvent<CameraProperty, String> event) {
				if (!StrKit.equals(event.getNewValue(), event.getOldValue())) {
					Camera camera = Camera.dao.findById(event.getRowValue().getId());
					if (camera != null) {
						camera.setName(event.getNewValue());
						camera.update();
						event.getRowValue().setName(event.getNewValue());
					}
				}
			}
		});

		TableColumn<CameraProperty, String> usernameColumn = new TableColumn<CameraProperty, String>("账号");
		usernameColumn.setMinWidth(150);
		usernameColumn.setCellValueFactory(new PropertyValueFactory<CameraProperty, String>("username"));
		usernameColumn.setCellFactory(TextFieldTableCell.<CameraProperty>forTableColumn());
		usernameColumn.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<CameraProperty, String>>() {
			public void handle(CellEditEvent<CameraProperty, String> event) {
				if (!StrKit.equals(event.getNewValue(), event.getOldValue())) {
					Camera camera = Camera.dao.findById(event.getRowValue().getId());
					if (camera != null) {
						camera.setUsername(event.getNewValue());
						camera.update();
						event.getRowValue().setUsername(event.getNewValue());
					}
				}
			}
		});

		TableColumn<CameraProperty, String> passwordColumn = new TableColumn<CameraProperty, String>("密码");
		passwordColumn.setMinWidth(150);
		passwordColumn.setCellValueFactory(new PropertyValueFactory<CameraProperty, String>("password"));
		passwordColumn.setCellFactory(TextFieldTableCell.<CameraProperty>forTableColumn());
		passwordColumn.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<CameraProperty, String>>() {
			public void handle(CellEditEvent<CameraProperty, String> event) {
				if (!StrKit.equals(event.getNewValue(), event.getOldValue())) {
					Camera camera = Camera.dao.findById(event.getRowValue().getId());
					if (camera != null) {
						camera.setPassword(event.getNewValue());
						camera.update();
						event.getRowValue().setPassword(event.getNewValue());
					}
				}
			}
		});
		
		TableColumn<CameraProperty, String> ipColumn = new TableColumn<CameraProperty, String>("IP");
		ipColumn.setMinWidth(250);
		ipColumn.setCellValueFactory(new PropertyValueFactory<CameraProperty, String>("ip"));
		ipColumn.setCellFactory(TextFieldTableCell.<CameraProperty>forTableColumn());
		ipColumn.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<CameraProperty, String>>() {
			public void handle(CellEditEvent<CameraProperty, String> event) {
				if (!StrKit.equals(event.getNewValue(), event.getOldValue())) {
					Camera camera = Camera.dao.findById(event.getRowValue().getId());
					if (camera != null) {
						camera.setIp(event.getNewValue());
						camera.update();
						event.getRowValue().setIp(event.getNewValue());
					}
				}
			}
		});
		
		
		TableColumn<CameraProperty, String> portColumn = new TableColumn<CameraProperty, String>("端口");
		portColumn.setMinWidth(60);
		portColumn.setCellValueFactory(new PropertyValueFactory<CameraProperty, String>("port"));
		portColumn.setCellFactory(TextFieldTableCell.<CameraProperty>forTableColumn());
		portColumn.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<CameraProperty, String>>() {
			public void handle(CellEditEvent<CameraProperty, String> event) {
				if (!StrKit.equals(event.getNewValue(), event.getOldValue())) {
					try {
						Camera camera = Camera.dao.findById(event.getRowValue().getId());
						if (camera != null) {
							camera.setPort(Integer.parseInt(event.getNewValue()));
							camera.update();
							event.getRowValue().setPort(event.getNewValue());
						}
					} catch (Exception e) {
						LayerUtil.open("必须是数字！", 110);
						event.getRowValue().setPort(event.getOldValue());
						cameraTableView.refresh();
					}
				}
			}
		});

		cameraTableView.getColumns().addAll(nameColumn, usernameColumn, passwordColumn, ipColumn,portColumn);
		cameraTableView.setItems(data);
		
		ProgressStage.of(RouteUtil.mainStage, new Task<Void>() {
			@Override
			protected Void call() throws Exception {
				Platform.runLater(new Runnable() {
					public void run() {
						List<Camera> cameras = Camera.dao
								.find("select * from " + Camera.TABLE_NAME );
						if (cameras != null && cameras.size() > 0) {
							for (Camera camera : cameras) {
								data.add(new CameraProperty(camera));
							}
						}

						cameraTableView.setItems(data);
						if(!isDestroy) {
							rotateTransitionOut = new RotateTransition(Duration.seconds(10), timerOutLinePane);
							rotateTransitionOut.setFromAngle(0);
							rotateTransitionOut.setToAngle(360);
							rotateTransitionOut.setByAngle(360); // 设置旋转的角度
							rotateTransitionOut.setCycleCount(Animation.INDEFINITE); // 设置旋转次数，我们需要旋转无数次
							rotateTransitionOut.setInterpolator(Interpolator.LINEAR);
							rotateTransitionOut.play();

							rotateTransitionIn = new RotateTransition(Duration.seconds(10), timerInLinePane);
							rotateTransitionIn.setFromAngle(360);
							rotateTransitionIn.setToAngle(0);
							rotateTransitionIn.setByAngle(360); // 设置旋转的角度
							rotateTransitionIn.setCycleCount(Animation.INDEFINITE); // 设置旋转次数，我们需要旋转无数次
							rotateTransitionIn.setInterpolator(Interpolator.LINEAR);
							rotateTransitionIn.play();
							startCountDown();
						}
					}
				});
				return null;
			}
		}, "查询配置中...").show();
		
	}
	
	
	public void add(ActionEvent event) {
		Button bu = (Button) event.getSource();
		bu.setVisible(false);
		Camera camera = new Camera();
		camera.setId(UuidUtil.getUUID());
		camera.setName("未命名");
		camera.setIp("");
		camera.setUsername("admin");
		camera.setPassword("123456");
		camera.setPort(0);
		if (camera.save()) {
			data.add(new CameraProperty(camera));
		}
		bu.setVisible(true);
	}

	public void delete(ActionEvent event) {
		Button bu = (Button) event.getSource();
		bu.setVisible(false);
		CameraProperty cameraProperty = cameraTableView.getSelectionModel().getSelectedItem();
		if (cameraProperty != null) {
			if (Camera.dao.deleteById(cameraProperty.getId())) {
				LayerUtil.open("删除成功！", 200);
				data.remove(cameraProperty);
			} else {
				LayerUtil.open("删除失败！", 500);
			}
		} else {
			LayerUtil.open("请选择行！", 110);
		}
		bu.setVisible(true);
	}
	
	public void startCountDown() {
		animation = new Timeline(new KeyFrame(Duration.millis(1000), new EventHandler<ActionEvent>() {
			public void handle(ActionEvent event) {
				if(RouteUtil.getTime()>0) {
					RouteUtil.setTime(RouteUtil.getTime() - 1);
					if (RouteUtil.getTime() == 0) {
						timerLabel.setText("0");
						LayerUtil.open("操作超时！", 999);
					} else if (RouteUtil.getTime() > 0) {
						timerLabel.setText(RouteUtil.getTime() + "");
					}
				}
				
			}
		}));
		animation.setCycleCount(Timeline.INDEFINITE);
		animation.play();
	}

	public void destroy() {
		if (animation != null) {
			animation.stop();
		}
		if (rotateTransitionOut != null) {
			rotateTransitionOut.stop();
		}
		if (rotateTransitionIn != null) {
			rotateTransitionIn.stop();
		}
	}

	public void exit(ActionEvent event) {
		if(!isDestroy) {
			isDestroy=true;
			Button bu = (Button) event.getSource();
			bu.setVisible(false);
			destroy();
			RouteUtil.goConfig();
		}
	}


}
